package com.atguigu.atcrowdfunding.web;

import com.atguigu.atcrowdfunding.bean.Permission;
import com.atguigu.atcrowdfunding.service.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * lcd  2020/4/2
 * Description:
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private PermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String contextPath = session.getServletContext().getContextPath();
        //拿到本次请求的url
        String requestURI = request.getRequestURI();
        requestURI=requestURI.replace(contextPath, "");
        //拿到当前用户所拥有的url
        Set<String> authUriSet= (Set<String>) session.getAttribute("authUriSet");
        List<Permission> permissionServiceAll = permissionService.findAll();
        Set<String> dbAllAuthSet = new HashSet<>();
        for (Permission permission : permissionServiceAll) {
            if (StringUtils.isNotBlank(permission.getUrl())) {
                dbAllAuthSet.add(permission.getUrl());
            }
        }
        System.out.println(contextPath);
        System.out.println(request.getContextPath());
        //请求的url如果在数据库里面,才需要进行鉴权
        if(dbAllAuthSet.contains(requestURI)){
            if (authUriSet.contains(requestURI)) {
                return true;
            }else{
                response.sendRedirect(contextPath+"/error");
                return false;
            }
        }else{
            return true;
        }

    }
}
